package problema041;

import java.util.HashSet;
import java.util.Set;

public class PandigitalPrime {
	//static Set<Integer> primos = new HashSet<Integer>();
	static Integer max = 0;
	static boolean[] isPrime;
	
	public static void main(String[] args){
		System.out.println(panPrime());
	}
	
	public static Integer panPrime(){
		//primos.add(2);
		Integer tam;
		/*for(int i = 3; i < 31426; i++){
			esPrimo(i);
		}*/
		sieveOfEratosthenes(987654322);
		for(Integer i = 987654322; i > 0; i--){
			tam = String.valueOf(i).length();
			if(esPan(i,tam)){
				if(isPrime[i]){
					return i;
				}
			}
		}
		return max;
	}

	public static void sieveOfEratosthenes(int n){
     // initially assume all integers are prime
     isPrime = new boolean[n + 1];
     for (int i = 2; i <= n; i++) {
         isPrime[i] = true;
     }
     // mark non-primes <= n using Sieve of Eratosthenes
     for (int i = 2; i*i <= n; i++) {
         // if i is prime, then mark multiples of i as nonprime
         // suffices to consider mutiples i, i+1, ..., n/i
         if (isPrime[i]) {
             for (int j = i; i*j <= n; j++) {
                 isPrime[i*j] = false;
             }
         }
     }
     // count primes
     int primes = 0;
     for (int i = 2; i <= n; i++) {
         if (isPrime[i]) primes++;
     }
     System.out.println("The number of primes <= " + n + " is " + primes);
 }
	
	public static boolean esPan(Integer n, Integer tam){
		Set<Integer> num = new HashSet<Integer>();
		int i = n;
		while(i != 0){
			if(num.contains(i % 10) || (i % 10) == 0) return false;
			num.add(i%10);
			i = i /10;
		}
		for(Integer j = 1; j <= tam; j++){
			if(!num.contains(j)) return false;
		}
		return true;		
		/*boolean[] cant = new boolean[9];
		int i = n;
		while(i != 0){
			if(cant[i % 10] || (i % 10) == 0) return false;
			cant[i % 10] = true;
			i = i /10;
		}		
		for(int j = 0; j < tam; j++){
			if(!cant[j]) return false;
		}
		return true;*/
	}
	
	/*public static boolean esPrimo(Integer num){
		Iterator<Integer> it = primos.iterator();
		int n = num, i = 0;
		while (it.hasNext()){
			i = it.next();
			if(n % i == 0) return false;
		}
		primos.add(num);
		return true;
	}*/
	
	/*public static boolean esPrimo(double num){
		double hasta = Math.sqrt(num);
		int hastaI = (int) hasta;
		for(int i = 2; i < hastaI; i++){
			if(num % i == 0) return false;
		}
		return true;
	}*/
	
	

}
